import React from 'react';
import moment from 'moment';
import { primaryColor } from '@/defaultSettings';
import { Button, Icon } from 'antd';
import DaySchedule from './DaySchedule';
import { checkIntersection, px2Time, formatStaticMap } from './utils';
import styles from './index.less';

const DATE_FORMAT = 'YYYY-MM-DD';
const DATE_FORMAT_HEAD = 'YYYY年M月D日 dddd';
const DATE_FORMAT_WEEK = 'D日 dddd';

const ROWS_NUM = 48;
const ROW_HEIGHT = 22;
const MIN_UNIT = 22;

const getWeekList = i => {
    const range = [0, 1, 2, 3, 4, 5, 6].map(item => {
        const day = moment()
            .add(i * 7, 'days')
            .weekday(item);

        return {
            // moment: day,
            date: day.format(DATE_FORMAT),
            weekday: day.format('dddd'),
            dateWeekday: day.format(DATE_FORMAT_WEEK)
        };
    });
    return range;
};

const Calendar = React.forwardRef(({ staticRangeMap }, ref) => {
    const [dateTimeObj, setDateTimeObj] = React.useState(null);
    const [tip, setTip] = React.useState({ first: true, show: true });
    const [nowIndex, setNowIndex] = React.useState(0);
    const weekdayList = React.useMemo(() => getWeekList(nowIndex), [nowIndex]);
    const rows = [...Array(24).keys()];

    const staticObj = React.useMemo(() => formatStaticMap(staticRangeMap, MIN_UNIT), [JSON.stringify(staticRangeMap)]);

    React.useImperativeHandle(ref, () => ({
        submit: () => {
            if (!dateTimeObj) return [true];
            const arr = Object.keys(dateTimeObj);
            if (arr.length === 0) return [true];
            let flag = false;
            const finalArr = [];
            arr.forEach(item => {
                const range = dateTimeObj[item] || [];
                const staticRange = staticObj[item] || [];
                range.forEach(it => {
                    finalArr.push({
                        startTime: `${item} ${px2Time(it.range[0], MIN_UNIT)}:00`,
                        endTime: `${item} ${px2Time(it.range[1], MIN_UNIT)}:00`
                    });
                    if (staticRange.some(it2 => checkIntersection(it2.range, it.range))) {
                        flag = true;
                    }
                });
            });
            return [flag, finalArr];
        }
    }));

    const handleWeekChange = v => {
        setNowIndex(nowIndex + v);
    };

    const handleToday = React.useCallback(() => {
        setNowIndex(0);
    }, []);

    const handleScheduleChange = o => {
        setDateTimeObj({
            ...dateTimeObj,
            ...o
        });
    };

    return (
        <div className={styles.calendarContainer}>
            <div className={styles.calendarHead}>
                <Button className={styles.todayBtn} disabled={nowIndex === 0} onClick={handleToday}>
                    今天
                </Button>
                {/* <div
                    className={styles.switchIcon}
                    style={nowIndex > 0 ? null : { cursor: 'not-allowed' }}
                    onClick={nowIndex > 0 ? () => handleWeekChange(-1) : null}
                >
                    <Icon type="caret-left" style={{ color: nowIndex > 0 ? primaryColor : 'rgba(0, 0, 0, 0.25)' }} />
                </div> */}
                <div className={styles.switchIcon} onClick={() => handleWeekChange(-1)}>
                    <Icon type="caret-left" style={{ color: primaryColor }} />
                </div>
                <div style={{ width: 200, textAlign: 'center' }}>
                    {moment()
                        .add(nowIndex * 7, 'days')
                        .format(DATE_FORMAT_HEAD)}
                </div>
                {/* <div
                    className={styles.switchIcon}
                    style={nowIndex < 2 ? null : { cursor: 'not-allowed' }}
                    onClick={nowIndex < 2 ? () => handleWeekChange(1) : null}
                >
                    <Icon type="caret-right" style={{ color: nowIndex < 2 ? primaryColor : 'rgba(0, 0, 0, 0.25)' }} />
                </div> */}
                <div className={styles.switchIcon} onClick={() => handleWeekChange(1)}>
                    <Icon type="caret-right" style={{ color: primaryColor }} />
                </div>
            </div>
            <div className={styles.weekday}>
                <div className={styles.hour}></div>
                {weekdayList.map(item => (
                    <div className={styles.hourItem} key={item.date}>
                        {item.dateWeekday}
                    </div>
                ))}
            </div>
            <div className={styles.mainSchedule} id="popoverWrap">
                <div className={styles.hourSchedule} style={{ background: '#F6F7F8' }}>
                    <span
                        style={{
                            position: 'absolute',
                            top: 2,
                            left: '50%',
                            transform: 'translateX(-50%)'
                        }}
                    >
                        00:00
                    </span>
                    {rows.map(rowIndex => (
                        <div key={rowIndex} className={styles.hourHeadItem}>
                            <span
                                style={{
                                    position: 'absolute',
                                    bottom: -10,
                                    left: '50%',
                                    transform: 'translateX(-50%)'
                                }}
                            >
                                {rowIndex + 1 < 10 ? '0' : ''}
                                {rowIndex + 1}:00
                            </span>
                        </div>
                    ))}
                </div>
                {weekdayList.map(item => (
                    <div className={styles.hourScheduleItem} key={item.date}>
                        <DaySchedule
                            date={item.date}
                            defaultRangeList={dateTimeObj?.[item.date] || []}
                            onChange={handleScheduleChange}
                            rowsNum={ROWS_NUM}
                            rowHeight={ROW_HEIGHT}
                            minUnit={MIN_UNIT}
                            staticRangeList={staticObj?.[item.date] || []}
                            tip={tip}
                            setTip={setTip}
                        />
                    </div>
                ))}
            </div>
        </div>
    );
});

export default Calendar;
